package com.ag.oa.core.controller;

import com.ag.oa.shiro.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/login")
    public String gotoLogin() {

        return "/login.html";
    }

    @PostMapping("/sys/toLogin")
    public String login(@RequestParam("username") String username, @RequestParam("password")
            String password, Map<String, Object> map) {

        try {
            // shiro
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                subject.login(token);
            }
        } catch (AuthenticationException ae) {
            // 日志记录登录失败
            map.put("loginErrorMsg", "用户名或密码错误");
            logger.error("登录失败: "+ ae.getMessage());
        }
        return "redirect:/index";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {

        ShiroUtil.logout();
        return "redirect:/login.html";
    }

}
